﻿namespace EyeOpen.ShellCommand.Windows
{
	using System;
	using System.Linq;
	using System.Windows.Forms;
	using EyeOpen.Diagnostics;

	public partial class MainForm : Form
	{
		public MainForm()
		{
			InitializeComponent();
		}

		private void ExecuteLinkLabelLinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
		{
			outputTextBox.Clear();

			var commandList =
				commandsTextBox.Text.Split("\r\n".ToArray(), StringSplitOptions.RemoveEmptyEntries)
					.Select(ParamterFromLine)
					.ToArray();

			new ShellProcess()
				.Execute(
					line => outputTextBox.Invoke(() => outputTextBox.Text += line + Environment.NewLine),
					() =>
							outputTextBox.Invoke(() =>
							                     	{
							                     		outputTextBox.SelectionStart = outputTextBox.Text.Length;
							                     		outputTextBox.ScrollToCaret();
							                     	}),
					commandList);
		}

		private ShellCommand ParamterFromLine(string line)
		{
			var spaceIndex = line.IndexOf(' ');

			var command = 
				(spaceIndex == -1) ? 
					new ShellCommand(line) : 
					new ShellCommand(line.Substring(0, spaceIndex), line.Substring(spaceIndex + 1));

			return command;
		}
	}
}
